package com.hh.jwtdemo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;

public class JwtUtil {

    /**
     *payload主体key
     */
    public static String subjectName;
    /**
     *密钥
     */
    public static String secret;
    /**
     * 过期时间
     */
    public static int expire;
    /**
     * 日期单位
     */
    public static int timeUnit;

    static {
        Properties properties = new Properties();
        try {
            properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties"));
            subjectName = properties.getProperty("myconfig.jwt.subjectName");
            secret = properties.getProperty("myconfig.jwt.secret");
            expire = Integer.valueOf(properties.getProperty("myconfig.jwt.expire"));
            timeUnit = Integer.valueOf(properties.getProperty("myconfig.jwt.timeUnit"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成token
     * @param payload
     * @return
     */
    public static String createToken (String payload){
        Calendar nowDate = Calendar.getInstance();
        nowDate.add(timeUnit, expire);
        //过期时间
        Date expireDate = nowDate.getTime();
        return JWT.create().withClaim(subjectName,payload)
                .withExpiresAt(expireDate).sign(Algorithm.HMAC256(secret));
    }

    /**
     * 获取token中的payload
     * @param token
     * @return
     */
    public static String getTokenPayload (String token) {
        return JWT.require(Algorithm.HMAC256(secret)).build()
                .verify(token).getClaim(subjectName).asString();
    }
}

